package edu.johnpank.libassistant.controllers

import edu.johnpank.libassistant.entity.Book
import edu.johnpank.libassistant.services.BookService
import edu.johnpank.libassistant.services.BorrowedBookService
import edu.johnpank.libassistant.services.UserService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.ComponentScan
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam

@Controller
@ComponentScan
class ReaderController(
    @Autowired
    private val bookService: BookService,
    private val borrowedBookService: BorrowedBookService,
    private val userService: UserService
) {

    //region showMainReaderPage
    @GetMapping("reader/reader_main_page")
    fun showMainReaderPage(): String{
        return "reader/reader_main_page"
    }
    //endregion

    //region showBorrowedBookForReader
    @GetMapping("/reader/borrowedBookList")
    fun showReaderBorrowBookList(model: Model): String{
        val authUserLogin = SecurityContextHolder.getContext().authentication.name
        val curUser = userService.getUserByLogin(authUserLogin).get()

        val readerBorrBookList = curUser.id?.let { borrowedBookService.getAllNotReturnedBookByReader(it) }
        val readerHoldBookList:MutableList<Book> = mutableListOf()

        if (readerBorrBookList != null) {
            for (borBook in readerBorrBookList){
                readerHoldBookList.add(bookService.getBookById(borBook.bookId))
            }
        }

        model.addAttribute("borrBookList", readerHoldBookList)

        return "/reader/read_borr_book_list_page"
    }
    //endregion

    //region readerFindBook
    @GetMapping("/reader/findBookPage")
    fun showReaderFindBookPage(model: Model): String{

        return "/reader/read_find_book_page"
    }

    @GetMapping("/reader/findBook")
    fun showReaderFindBookResultPage(@RequestParam("search") search: String,
                               model: Model): String{

        model.addAttribute("books", bookService.findBookByContainedString(search))
        return "/reader/read_book_list_page"
    }

    //endregion

}